use std::cell::OnceCell;
use std::collections::HashMap;
use std::net::SocketAddr;
use std::ptr::addr_of;
use std::sync::{Arc,  RwLock};
use std::thread::sleep;
use std::time::Duration;
use lazy_static::lazy_static;
use serde::Serialize;
use tokio::io::{AsyncReadExt, AsyncWriteExt, BufReader, BufWriter};
use tokio::net::{TcpListener, TcpStream};
use tokio::net::tcp::{OwnedWriteHalf, WriteHalf};
use tokio::sync::{mpsc, Mutex};
use tokio::sync::mpsc::{Receiver, Sender};
use tokio::task::JoinHandle;
use tokio::time::{interval, timeout};
/* 开始服务 */
lazy_static! {
    static ref  CLIENTS_MAP:Arc<RwLock<HashMap<SocketAddr, Sender<String>>>> = Arc::new(RwLock::new(HashMap::new()));
}

pub async fn start_server() {
    let tcp = TcpListener::bind("127.0.0.1:5657").await.unwrap();

    loop {
        let (tcp_steam, socket_addr) = tcp.accept().await.unwrap();
        let (tx, mut rx) = mpsc::channel(1024);

        CLIENTS_MAP.write().unwrap().insert(socket_addr, tx);

        tokio::spawn(async move {
            handle_client(tcp_steam, socket_addr, rx).await;
        });
    }
}

async fn handle_client(mut tcp_steam: TcpStream, socket_addr: SocketAddr, mut rx: Receiver<String>) {
    let (read, mut write) = tcp_steam.into_split();
    let mut buf_reader = BufReader::new(read);

    let  write_arc = Arc::new(Mutex::new(write));
    let  write_arc_copy = write_arc.clone();

    tokio::spawn(async move {
        while let Some(pc) = rx.recv().await {
            write_arc.lock().await.write_all(pc.as_bytes()).await.unwrap();
        }
    });
    let (tx, mut rx) = mpsc::channel(2);
    tokio::spawn(async move{
        // sleep(40000);
        loop {
           write_arc_copy.lock().await.write_all("".as_bytes()).await.unwrap();
           match timeout(Duration::from_secs(5),  rx.recv()).await {
               Ok(_) =>{

               }
               Err(_) =>{
                   write_arc_copy.lock().await.shutdown().await.expect("TODO: panic message");
               }
           };
        }
    });

    let mut buffer: [u8; 1024] = [0; 1024];
    let mut list: Vec<u8> = Vec::new();

    loop {
        match buf_reader.read(&mut buffer).await {
            Ok(n) => {
                if n == 0 {
                    // n = 0 的时候，说明客户端断开了链接
                    break;
                }
                &list.extend_from_slice(&buffer[..n]);
                if n < 1024 {

                    println!("打印出接收到的数据为： {:?}", String::from_utf8_lossy(&list));
                    // tx.send(TcpSenderConfig { content: "阅读后即可焚毁".to_string() }).await.unwrap();
                    send_tcp_data(&socket_addr, "阅读后即可焚毁，可还行".to_string());

                    &list.clear();
                }
                // tx.send(true).await.unwrap();
            }
            Err(_) => {
                break;
            }
        }
    }

    println!("请求断开了");
    CLIENTS_MAP.write().unwrap().remove(&socket_addr);
}


pub fn send_tcp_data(addr:&SocketAddr, content:String){
    if CLIENTS_MAP.read().unwrap().is_empty() {
        println!("为空发送消息失败。");
        return;
    }
    if let Some(tx1) = CLIENTS_MAP.read().unwrap().get(addr) {
        tx1.try_send(content).unwrap();
        // println!("打印出接收到的数据为： {:?}", tx1);
    }else {
        println!("没有此消息，发送消息失败。");
    }
}

#[derive(Serialize, Debug)]
pub(crate) struct TcpSenderConfig {
    content: String,
}
















